<script setup>
import {getPageProducts} from '@/api/ShopDatabase/index.js';
import { useDistInfoStore } from '@/stores/dict.js';
import { StoreManagementList } from '@/api/Marketing/coupon.js'
import { uniqueFunc } from '@/utils/common.js'
const distInfoStore = useDistInfoStore();

// 经营品牌数据
const operBrandList = computed(()=>{
    return distInfoStore.getDistInfo("经营品牌").map(lis=>{
        return {
            value:lis.id,
            label:lis.permissionName
        }
    })
})

//门店分组列表 
const storeList = computed(()=>{
    return distInfoStore.getDistInfo("门店分组").map(lis=>{
        return {
            value:lis.id,
            label:lis.permissionName
        }
    })
})



const props = defineProps({
    
})
const emits = defineEmits(["backStoreValue"]);
const storeFlag = ref(false);

const formInline = ref([


    {
      type: "input",
      prop: "keywords",
      placeholder: "门店名称/ID",
      label: "",
      model: "",
      width:180
    },
    {
      type: "input",
      prop: "enterpriseName",
      placeholder: "所属商户",
      label: "",
      model: "",
      width:180
    },
    {
        type: "select",
        placeholder: "经营方式",
        label: '',
        prop: 'managementWays',
        multiple:true,
        data:[
            {
                label:"直营",
                value:1
            },
            {
                label:"加盟",
                value:2
            }
        ],
        model: [],
        clearable:true,
        width:180 
    },
    {
        type: "select",
        placeholder: "经营品牌",
        label: '',
        prop: 'brandIds',
        multiple:true,
        data:operBrandList.value,
        model: [],
        width:180 
    },
    {
        type: "select",
        placeholder: "门店分组",
        label: '',
        prop: 'storeGroupIds', 
        multiple:true,
        data:storeList.value,
        model: [],
        width:180 
    },
    {
      type: "input",
      prop: "address",
      placeholder: "所属地区",
      label: "",
      model: "",
      width:180 
    },

])
const btnLefts = ref([]);
const btnRights = ref([])
const tableConfig = ref([
    {
      prop: "code",
      label: "门店ID",
      width:200
    },
    {
      type:'slot',
      label: "门店名称",
      prop: "storeName",
      width: 150,
      needHeader: true,
      slotHeaderName: 'storeNameHeader',
      slotName: 'storeName',
      width:200
    },

    // {
    //     type: 'slot',
    //     label: '全部理疗馆',
    //     prop: 'physiotherapyHall',
    //     width: 150,
    //     needHeader: true,
    //     slotHeaderName: 'physiotherapyHallHeader',
    //     slotName: 'physiotherapyHall'
    // },  
    // {
    //     type: 'slot',
    //     label: '全部商城',
    //     prop: 'shop',
    //     width: 150,
    //     needHeader: true,
    //     slotHeaderName: 'shopHeader',
    //     slotName: 'shop'
    // }, 
   

    {
      prop: "enterpriseName",
      label: "所属商户",
      width:200
    },
    {
      prop: "managementWay",
      label: "经营方式",
      format:(val) => {
        return val ? val == 1 ? '直营' : '加盟' : '-'
      },
      width:200
    },
    {
      prop: "brandId",
      label: "经营品牌",
      format: (val) => {
       if(val){
        let newArray = val.split(',')
        let matches = []
        for (const valueToMatch of newArray) {
            const matchingItem = operBrandList.value.find(item => item.value === valueToMatch);
            if (matchingItem) { 
                matches.push(matchingItem.label);
            }
          }
          return matches.join(",");
        }else{
          return '-'
        }
       },
      width:200
    },

    
    {
      prop: "storeGroupId",
      label: "门店分组",
      format: (val) => {
       if(val){
        let newArray = val.split(',')
        let matches = []
        for (const valueToMatch of newArray) {
            const matchingItem = storeList.value.find(item => item.value === valueToMatch);
            if (matchingItem) { 
                matches.push(matchingItem.label);
            }
          }
          return matches.join(",");
        }else{
          return '-'
        }
       },
      width:200
    },
    {
      prop: "addr",
      label: "所属地区",
      width:200
    },
])
const allStore = ref(false)
const isIndeterminateStore = ref(false)

const allHall = ref(false);
const isIndeterminateHall = ref(false);

const allShop = ref(false);
const isIndeterminateShop = ref(false);

const tableLoading = ref(false)
const totalPage = ref(0)
const tableData = ref([]);
const productFlag = ref(false);
const checkDataPhysiotherapyHall = ref([]);
const checkDataShop = ref([]);
const checkDataStore = ref([]);
const seachTable = ref(null);
const disableId = ref({
    hallId:[],
    shopId:[],
    storeId:[]
});
const openModal = (arr = [],disable)=>{
    checkDataPhysiotherapyHall.value = arr.filter(value=>{
        return value.isHall == true;
    });
    checkDataShop.value = arr.filter(value=>{
        return value.isShop == true;
    })
    checkDataStore.value = arr.filter(value=>{
        return value.isStore == true;
    });
    if(disable){
        disableId.value.hallId = disable.hallId;
        disableId.value.shopId = disable.shopId;
        disableId.value.storeId = disable.storeId;
    }
    storeFlag.value = true;
    
}
const handlerSearch = async (formInline)=>{
    
    tableLoading.value = true;
    try{
        const res = await StoreManagementList(formInline);
        totalPage.value = Number(res.total);
        let checkHallIds= checkDataPhysiotherapyHall.value.map(value=>value.id);
        let checkShopIds= checkDataShop.value.map(value=>value.id);
        let checkStoreIds = checkDataStore.value.map(value=>value.id);
        tableData.value = res.records.map(lis=>{
            
            return {
                ...lis,
                hallId:'hall'+lis.id,
                shopId:'shop'+lis.id,
                storeId:'store'+lis.id,
                isHall:checkHallIds.includes(lis.id),
                isShop:checkShopIds.includes(lis.id),
                isStore: checkStoreIds.includes(lis.id),
            }
        })
        nextTick(()=>{
            fullAttrValue();
        })
        tableLoading.value = false;
    }catch(e){
        tableLoading.value = false;
    }
}
const handleCheckAllHall = (value)=>{

    let col = allHall.value?tableData.value:false;
    if(col.length>0){
        checkDataPhysiotherapyHall.value = uniqueFunc([...checkDataPhysiotherapyHall.value,...col,],'hallId').filter(item=>!disableId.value.hallId.includes(item.id));
        
    }else{
        let ids = tableData.value.map(value=>value.hallId);
        removeData(ids);
    }
    fullAttrValue();
}

const handleCheckAllStore = (value)=>{

let col = allStore.value?tableData.value:[];
if(col.length>0){
    checkDataStore.value = uniqueFunc([...checkDataStore.value,...col,],'storeId').filter(item=>!disableId.value.storeId.includes(item.id));
    
}else{
    let ids = tableData.value.map(value=>value.storeId);
    removeStoreData(ids);
}
fullAttrValue();
}

const handleCheckStore = (value,row)=>{
let index = checkDataStore.value.map(value=>value.storeId).indexOf(row.storeId);
if(index >=0){
    removeStoreData([row.storeId]);
}else{
    checkDataStore.value = uniqueFunc([...checkDataStore.value,row],'storeId');
}

fullAttrValue();
}
const handleCheckHall = (value,row)=>{

    let index = checkDataPhysiotherapyHall.value.map(value=>value.hallId).indexOf(row.hallId);
    if(index >=0){
        removeData([row.hallId]);
    }else{
        checkDataPhysiotherapyHall.value = uniqueFunc([...checkDataPhysiotherapyHall.value,row],'hallId');
    }

    fullAttrValue();
}
const fullAttrValue = ()=>{
    let hallIds = checkDataPhysiotherapyHall.value.map(value=>value.hallId);
    let shopIds = checkDataShop.value.map(value=>value.shopId);
    let storeIds = checkDataStore.value.map(value=>value.storeId);
    let selectHallNum = 0;
    let selectShopNum = 0;
    let selectStoreNum = 0;
    tableData.value.forEach(lis=>{
        lis.isHall = false;
        lis.isShop = false;
        lis.isStore = false
    })
    tableData.value.forEach(lis=>{
        if(hallIds.includes(lis.hallId)){
            lis.isHall = true;
            selectHallNum++
        }
        if(shopIds.includes(lis.shopId)){
            lis.isShop = true;
            selectShopNum++
        }
        if(storeIds.includes(lis.storeId)){
            lis.isStore = true;
            selectStoreNum++
        }
    })
    if(selectHallNum >=tableData.value.length){
        allHall.value = true;
    }else{
        allHall.value = false;
    }
    if(selectHallNum>0 && selectHallNum<tableData.value.length){
        isIndeterminateHall.value = true;
    }else{
        isIndeterminateHall.value = false;

    }


    if(selectShopNum >=tableData.value.length){
        allShop.value = true;
    }else{
        allShop.value = false;
    }
    if(selectShopNum>0 && selectShopNum<tableData.value.length){
        isIndeterminateShop.value = true;
    }else{
        isIndeterminateShop.value = false;

    }

    
    if(selectStoreNum >=tableData.value.length){
        allStore.value = true;
    }else{
        allStore.value = false;
    }
    if(selectStoreNum>0 && selectStoreNum<tableData.value.length){
        isIndeterminateStore.value = true;
    }else{
        isIndeterminateStore.value = false;

    }
}
const handleCheckAllShop = (value)=>{
    let col = allShop.value?tableData.value:false;
    if(col.length>0){
        checkDataShop.value = uniqueFunc([...checkDataShop.value,...col,],'shopId').filter(item=>!disableId.value.shopId.includes(item.id));
    }else{
        let ids = tableData.value.map(value=>value.shopId);
        removeDataShop(ids);
    }
    fullAttrValue();
}
const handleCheckShop = (value,row)=>{
    let index = checkDataShop.value.map(value=>value.shopId).indexOf(row.shopId);
    if(index >=0){
        removeDataShop([row.shopId]);
    }else{
        checkDataShop.value = uniqueFunc([...checkDataShop.value,row],'shopId');
    }

    fullAttrValue();
}
//移除未选中的数据
const removeData = (ids)=>{
    checkDataPhysiotherapyHall.value = checkDataPhysiotherapyHall.value.filter(value=>ids.indexOf(value.hallId) == -1);
};
//移除未选中的数据
const removeDataShop = (ids)=>{
    checkDataShop.value = checkDataShop.value.filter(value=>ids.indexOf(value.shopId) == -1);
};

const removeStoreData = (ids)=>{
    checkDataStore.value = checkDataStore.value.filter(value=>ids.indexOf(value.storeId) == -1);
}
const confrimStore = ()=>{
    //...checkDataPhysiotherapyHall.value,...checkDataShop.value, 
    let resultArray =[...checkDataStore.value];
    resultArray = uniqueFunc(resultArray,'id');
    let checkHallIds= checkDataPhysiotherapyHall.value.map(value=>value.id);
    let checkShopIds= checkDataShop.value.map(value=>value.id);
    let checkStoreIds= checkDataStore.value.map(value=>value.id);
    resultArray = resultArray.map(lis=>{
        return{
            ...lis,
            isHall:  checkStoreIds.includes(lis.id) ,//checkHallIds.includes(lis.id),
            isShop: checkStoreIds.includes(lis.id) ,  // checkShopIds.includes(lis.id),
            isStore: checkStoreIds.includes(lis.id)
        }
    })
    emits("backStoreValue",resultArray);
    storeFlag.value = false;
}

defineExpose({openModal})
</script>
<template>
    <el-dialog v-model="storeFlag" title="适用门店及业务" width="1000px">
        <div style="width:100%;height:500px" v-if="storeFlag">
            <SeachTable 
                :tableType="1"
                ref="seachTable"
                :forms="formInline"
                :btnLefts="btnLefts"
                :btnRights="btnRights"
                :tableLoading="tableLoading"
                :tableConfig="tableConfig"
                :tableData="tableData"
                :totalPage="totalPage"
                @handlerSearch="handlerSearch"
                :showLine="false"
                :showBtn="false"

            >
                <template #storeNameHeader>
                    <el-checkbox
                        v-model="allStore"
                        :indeterminate="isIndeterminateStore"
                        @change="handleCheckAllStore"
                        >
                            <span style="font-size: 14px;color: #000;font-weight: bold;">全部门店</span>
                        </el-checkbox
                    >
                </template>
                <template #storeName="{row}">
                    <el-checkbox
                        v-model="row.isStore"
                        :disabled="disableId.storeId.includes(row.id)"
                        @change="value=>handleCheckStore(value,row)"
                    >
                        {{ row.storeName }}
                    </el-checkbox>
                </template>


                <template #physiotherapyHallHeader>
                    <el-checkbox
                        v-model="allHall"
                        :indeterminate="isIndeterminateHall"
                        @change="handleCheckAllHall"
                        >
                            <span style="font-size: 14px;color: #000;font-weight: bold;">全部理疗馆</span>
                        </el-checkbox
                    >
                </template>
                <template #physiotherapyHall="{ row }">
                    <el-checkbox
                        v-model="row.isHall"
                        :disabled="disableId.hallId.includes(row.id)"
                        @change="value=>handleCheckHall(value,row)"
                    >
                        理疗馆
                    </el-checkbox>
                </template>
                <template #shopHeader>
                    <el-checkbox
                        v-model="allShop"
                        :indeterminate="isIndeterminateShop"
                        @change="handleCheckAllShop"
                        >
                            <span style="font-size: 14px;color: #000;font-weight: bold;">全部商城</span>
                        </el-checkbox
                    >
                </template>
                <template #shop="{ row }">
                    <el-checkbox
                        v-model="row.isShop"
                        :disabled="disableId.shopId.includes(row.id)"
                        @change="value=>handleCheckShop(value,row)"
                    >
                        商城
                    </el-checkbox>
                </template>
            </SeachTable>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="storeFlag = false">取消</el-button>
                <el-button type="primary" @click="confrimStore()">确定</el-button>
            </div>
        </template>
    </el-dialog>
</template>
<style lang="less" scoped>
:deep(.search-line){
    padding:0;
}
:deep(.search-table .table){
    padding:0;
}
:deep(.el-table__header){
    tr{
        th{
            &:last-child{
                .cell{
                    border-right: 0px;
                }
            }
        }
    }
}
</style>
